package com.cn.ant.common.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * 公共的HttpClient处理类
 * Created by 黄根华 on 2015/4/6.
 */
public class HttpClientUtils {

    protected static CloseableHttpClient httpClient = null;

    static {
        if (httpClient == null) {
            httpClient = HttpClients.createDefault();
        }
    }

    /**
     * get请求
     *
     * @param url
     * @param timeOut
     * @return
     */
    public static String get(String url, int timeOut) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeOut).build();
        HttpGet getMethod = new HttpGet(url);
        getMethod.setConfig(requestConfig);
        //执行get请求
        try {
            HttpResponse httpResponse = httpClient.execute(getMethod);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status == 200) {
                //获取响应消息实体
                HttpEntity entity = httpResponse.getEntity();
                String body = EntityUtils.toString(entity, "UTF-8");
                return body;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * get请求,返回jsonarray
     *
     * @param url
     * @param timeOut
     * @return
     */
    public static JSONArray getByJson(String url, int timeOut) {
        String body = get(url, timeOut);
        JSONArray ja = JSONArray.fromObject("[" + body + "]");
        return ja;
    }

    /**
     * post方法
     *
     * @param url:请求地址
     * @param params:请求参数
     * @return 返回处理结果
     */
    public static String post(String url, Map<String, String> params) {
        String res = null;
        HttpPost httpPost = new HttpPost(url);//1.创建post方法
        List<NameValuePair> paramLis = new ArrayList<NameValuePair>(); //post请求参数
        CloseableHttpResponse response = null;
        try {
            //参数转换
            if (params == null) {
                params = new HashMap<String, String>();
            }
            Set<Map.Entry<String, String>> entries = params.entrySet();
            if (entries != null) {
                Iterator<Map.Entry<String, String>> it = entries.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    paramLis.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(paramLis, "UTF-8"));
            response = httpClient.execute(httpPost);//远程调用
            HttpEntity entity = response.getEntity();//结束响应报文
            if (entity != null) {
                res = EntityUtils.toString(entity, "UTF-8");//获取响应报文体
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    /**
     * 通过StringEntity发送post
     *
     * @param url
     * @param parameters
     * @return
     */
    public static String post(String url, String parameters) {
        String res = null;
        HttpPost httpPost = new HttpPost(url);//1.创建post方法
        CloseableHttpResponse response = null;
        try {
            // 建立一个NameValuePair数组，用于存储欲传送的参数
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);//远程调用
            HttpEntity entity = response.getEntity();//结束响应报文
            if (entity != null) {
                res = EntityUtils.toString(entity, "UTF-8");//获取响应报文体
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    /**
     * post 请求
     *
     * @param url:请求调用地址
     * @param params:请求参数
     * @return:JSON对象
     */
    public static JSONObject postByJson(String url, Map<String, String> params) {
        String body = post(url, params);
        JSONObject jo = JSONObject.fromObject(body);
        return jo;
    }

    /**
     * post 请求
     * @param url：请求调用地址
     * @param parameters：请求参数
     * @return
     */
    public static JSONObject postByJson(String url, String parameters) {
        String body = post(url, parameters);
        JSONObject jo = JSONObject.fromObject(body);
        return jo;
    }

    /**
     * get发送请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String get(String url, Map<String, String> params) {
        String res = null;
        HttpGet httpGet = null;
        List<NameValuePair> paramLis = new ArrayList<NameValuePair>();
        CloseableHttpResponse response = null;
        try {
            //参数转换
            if (params == null) {
                params = new HashMap<String, String>();
            }
            Set<Map.Entry<String, String>> entries = params.entrySet();
            if (entries != null) {
                Iterator<Map.Entry<String, String>> it = entries.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    paramLis.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(paramLis, "UTF-8"));
            httpGet = new HttpGet(url + "?" + paramStr);
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                res = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    /**
     * get 请求
     *
     * @param url
     * @param params
     * @return:JSONObject对象
     */
    public static JSONObject getByJson(String url, Map<String, String> params) {
        String body = get(url, params);
        JSONObject jo = JSONObject.fromObject(body);
        return jo;
    }

    public static void main(String[] args) {
        String url = "https://api.weixin.qq.com/cgi-bin/menu/get";
        Map<String, String> params = new HashMap<>();
        params.put("access_token", "PcJ-DYrFcXR4jCCjUkwVQ7459OymPhSO46kMTfmBXJYpCCcRJCD0CjSIWCztfgClgTrz_O6ugrmdae5eyRtsJNFE5X5apeVmkzfPYBzbl1o");
        JSONObject ja = getByJson(url, params);
        System.out.println(ja.size());
    }

}
